package com.yin.waimai.service.impl;

import com.yin.waimai.dto.RegistrationRequestDTO;
import com.yin.waimai.dto.DeliveryPersonDTO; // 添加这一行
import com.yin.waimai.enums.DeliveryPersonStatus; // 添加这一行
import com.yin.waimai.enums.Role; // 假设你使用了 Role 枚举
import com.yin.waimai.model.User;
import com.yin.waimai.repository.UserRepository;
import com.yin.waimai.service.UserService;
import com.yin.waimai.service.DeliveryPersonService; // 添加这一行
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.Set;
import com.yin.waimai.dto.UserDTO;
import java.util.List;
import java.util.stream.Collectors;

@Service // 标记为 Spring Service 组件
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final DeliveryPersonService deliveryPersonService; // 添加这一行

    @Autowired
    public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder, 
                          DeliveryPersonService deliveryPersonService) { // 修改构造函数
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
        this.deliveryPersonService = deliveryPersonService; // 添加这一行
    }
    
    @Override
    @Transactional // 确保用户创建和角色设置在同一事务中
    public User registerNewUser(RegistrationRequestDTO registrationRequest) throws IllegalStateException {
        logger.info("Attempting to register new user with username: {}", registrationRequest.getUsername());

        if (userRepository.existsByUsername(registrationRequest.getUsername())) {
            logger.warn("Registration failed: Username {} already exists.", registrationRequest.getUsername());
            throw new IllegalStateException("Error: Username is already taken!");
        }

        User newUser = new User();
        newUser.setUsername(registrationRequest.getUsername());
        newUser.setPassword(passwordEncoder.encode(registrationRequest.getPassword())); // 加密密码

        // 设置角色
        Set<String> roles = new HashSet<>();
        
        // 根据注册请求中的角色字段设置用户角色
        if (registrationRequest.getRole() != null && registrationRequest.getRole().equals("delivery_person")) {
            // 如果是配送员角色
            roles.add(Role.DELIVERY_PERSON.getAuthority());
            logger.info("Registering user {} as a delivery person", registrationRequest.getUsername());
        } else {
            // 默认为普通用户角色
            roles.add(Role.USER.getAuthority());
        }
        
        newUser.setRoles(roles);

        User savedUser = userRepository.save(newUser);
        logger.info("User {} registered successfully with ID: {}", savedUser.getUsername(), savedUser.getId());
        
        // 如果是配送员，创建对应的配送员记录
        if (roles.contains(Role.DELIVERY_PERSON.getAuthority())) {
            // 创建配送员记录
            DeliveryPersonDTO deliveryPersonDTO = new DeliveryPersonDTO();
            deliveryPersonDTO.setName(savedUser.getUsername());
            
            // 生成一个唯一的电话号码
            String uniquePhone = "13800" + System.currentTimeMillis() % 10000000;
            try {
                // 确保电话号码唯一
                while (deliveryPersonService.findByPhone(uniquePhone).isPresent()) {
                    Thread.sleep(10); // 短暂延迟以改变时间戳
                    uniquePhone = "13800" + System.currentTimeMillis() % 10000000;
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            
            deliveryPersonDTO.setPhone(uniquePhone);
            deliveryPersonDTO.setStatus(DeliveryPersonStatus.OFFLINE); // 初始状态为离线
            
            // 调用配送员服务创建配送员记录
            // 不要捕获异常，让它传播出去触发事务回滚
            deliveryPersonService.createDeliveryPerson(deliveryPersonDTO);
            logger.info("Created delivery person record for user {} with phone {}", savedUser.getUsername(), uniquePhone);
        }
        
        return savedUser;
    }
    
    @Override
    public List<UserDTO> findAllUsers() {
        logger.info("Finding all users");
        return userRepository.findAll().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    public long countUsers() {
        logger.info("Counting all users");
        return userRepository.count();
    }
    
    /**
     * 将User实体转换为UserDTO
     */
    private UserDTO convertToDTO(User user) {
        if (user == null) {
            return null;
        }
        
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setRoles(user.getRoles());
        
        return dto;
    }
}